<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Zone extends Model
{
    //
    protected $table = 'zone';

    public $timestamps = false;

    protected $guarded = [''];

    /**
     *获取父地区
     */
    public function zone()
    {
        return $this->belongsTo('App\Models\Zone', 'upid', 'id');
    }

    /**
     *获取子地区
     */
    public function sZone()
    {
        return $this->hasMany('App\Models\Zone', 'id', 'upid');
    }


    /*
	 * 获取热点推荐的zone
	 */
    static function getAlphaZone(){
    	$zones = array();
    	$zones['ABCDEF'] = Zone::whereRaw("(alpha='A' or alpha='B' or alpha='C' or alpha='D' or  alpha='E' or  alpha='F') and recommend = 1 ")->get();
    	$zones['GHIJ'] = Zone::whereRaw("(alpha='G' or alpha='H' or alpha='I' or alpha='J') and recommend = 1  ")->get();
    	$zones['KLMN'] = Zone::whereRaw("(alpha='K' or alpha='L' or alpha='M' or alpha='N') and recommend = 1  ")->get();
    	$zones['OPQR'] = Zone::whereRaw("(alpha='O' or alpha='P' or alpha='Q' or alpha='R') and recommend = 1  ")->get();
    	$zones['STUV'] = Zone::whereRaw("(alpha='S' or alpha='T' or alpha='U' or alpha='V') and recommend = 1  ")->get();
    	$zones['WXYZ'] = Zone::whereRaw("(alpha='W' or alpha='X' or alpha='Y' or alpha='Z') and recommend = 1  ")->get();
    	return $zones;
    }
    
    /**
     * 获得城市
     */
    static function getZone($zone_id,$all_name=1) {
		if(!$zone_id)
			return "暂无";
    	$zone = Zone::where('id','=',$zone_id)->first();
    	if ($zone->upid) {
    		$upZone = Zone::where('id','=',$zone->upid)->first();
    		return $all_name ? $upZone->name . ' ' . $zone->name : $zone->name;
    	}
    	else {
    		return $zone->name;
    	}
    	return "暂无";
    }
    /**
     * 查询城市ID
     */
    static function SelectZone($zone_id){

        $zone_ids =  \Cache::has('zone_'.$zone_id) ? \Cache::get('zone_'.$zone_id) : false;

        if($zone_ids === false){

            $zones = Zone::where('upid',$zone_id)->get();
            foreach ($zones as $key => $vo) {
                $zone_ids[$key] = $vo->id;
            }
            $zone_ids[] = $zone_id;
        }
        
        return $zone_ids;
    }
    /*
     * 获取全部地区对象
     */
    static function selectAllZones(){
    	if(!Cache::has('all_zone')){
    		$zones=Zone::whereRaw("status=1 and name not in ('钓鱼岛地区')")->get();
    		Cache::forever('all_zone', $zones,1);
    	}
    	return Cache::get('all_zone');
    }
    
    static function cache($cache = 0){
    	$zones =  \Cache::has('zones') ? \Cache::get('zones') : false;
    	
    	if ($zones === false || $cache)
    	{
    		$data = array();
    		$zones = self::where('status',1)->get()->toArray();
    		foreach ($zones as $zone) {
    			$data[$zone['id']] = $zone;
    		}
    		$zones = $data;
    		\Cache::add('zones', $data,86400);
    	}
    	return $zones;
    }
}
